package com.coincalf.wallet.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.coincalf.framework.dto.CoinRechargeDTO;
import com.coincalf.framework.http.Response;
import com.coincalf.framework.utils.SignUtil;
import com.coincalf.wallet.entity.CoinRecharge;
import com.coincalf.wallet.service.AddressPoolService;
import com.coincalf.wallet.service.CoinRechargeService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 用户充值,当前用户充值成功之后添加数据到这个表,充值一般无手续费.当status为1的时候表示充值成功 前端控制器
 * </p>
 *
 * @author crow
 * @since 2018-05-16
 */
@RestController
@RequestMapping("/recharge")
@Slf4j
@Api(value = "用户币种充值", description = "用户币种充值")
public class CoinRechargeController {

    @Autowired
    private CoinRechargeService coinRechargeService;
    @Autowired
    private CommonController commonController;


    /**
     * 获取充值记录
     *
     * @param coinId 币种ID
     * @param page   分页参数
     * @return
     */
    @GetMapping("/record")
    @ApiOperation(value = "COIN-RECHARGE-002 获取充值记录", notes = "获取充值记录", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页大小", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "coinId", value
                    = "币种ID", dataType = "long", paramType = "query")
    })
    //@PreAuthorize("isAuthenticated()")
    public Response rechargeRecord(
            HttpServletRequest request,
            @RequestParam("coinId") long coinId,
            @ApiIgnore Page<CoinRecharge> page
    ) {
        //Long userId = commonController.getUserId(request);
        Long userId = commonController.getUserId(request);
        EntityWrapper<CoinRecharge> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userId);
        if (coinId != 0L) {
            wrapper.eq("coin_id", coinId);
        }

        wrapper.orderBy("created", false);
        Page<CoinRecharge> coinRechargePage = coinRechargeService.selectPage(page, wrapper);
        return Response.ok(coinRechargePage);
    }

    /**
     * 查询充币待入账的记录
     *
     * @return
     */
    @GetMapping("/pending")
    public List<CoinRechargeDTO> queryPendingRecord() {
        return coinRechargeService.queryPendingRecord();
    }

    /**
     * 充值成功
     *
     * @param coinRecharge 充值记录
     * @return
     */
    @PutMapping("/success")
    public boolean modifyRechargeStatus(@RequestBody CoinRechargeDTO coinRecharge) {
        if (coinRecharge.getSign() == null || StringUtils.isBlank(coinRecharge.getSign().getSign())) {
            log.warn("签名不能为空");
            return false;
        }
        boolean b = SignUtil.verifySign(
                coinRecharge.getSign().getCurrentTime(),
                coinRecharge.getSign().getRandomNum(),
                coinRecharge.getSign().getSign()
        );
        if (!b) {
            log.warn("签名验证失败");
            return false;
        }
        return coinRechargeService.modifyRechargeStatus(coinRecharge.getId(), coinRecharge.getStatus(), coinRecharge.getCollected());
    }

    @Autowired
    private AddressPoolService addressPoolService;

    @ApiOperation(value = "COIN-RECHARGE-002 数据库地址池新增地址", notes = "数据库地址池新增地址", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "coinName", value = "币种名称", dataType = "String", paramType = "query", example = "BTC"),
            @ApiImplicitParam(name = "amount", value = "数量", dataType = "int", paramType = "query", example = "10"),
    })
    @PostMapping("addAddress")
    public Object addAddress(int amount, String coinName, String currentTime, String randomNum, String sign) {
        if (StringUtils.isBlank(currentTime) || StringUtils.isBlank(randomNum) || StringUtils.isBlank(sign)) {
            return Response.err(-100, "签名验证失败");
        }
        if (!SignUtil.verifySign(currentTime, randomNum, sign)) {
            return Response.err(-100, "签名验证失败");
        }
        return Response.ok(addressPoolService.addAddress(coinName, amount));
    }

}

